package com.power.ding.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.utils.ExcelUtil;
import com.power.ding.api.IDi_rel_dept_targetFeign;
import com.power.ding.model.Di_rel_dept_target;
import com.power.ding.model.Di_user;
import com.power.ding.model.pageInfo.Di_rel_dept_targetPageInfo;
import com.power.ding.service.Di_rel_dept_targetService;
import com.power.ding.service.Di_userService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;



/**
 *   司法组织机构-被申请人控制器
 */

//@Slf4j
//@PowerLog
@RestController
@Api(value = "Di_rel_dept_targetController",tags={"司法组织机构-被申请人"})
public class Di_rel_dept_targetController implements IDi_rel_dept_targetFeign{

    @Resource
    private Di_rel_dept_targetService di_rel_dept_targetService;

    @Resource
    private Di_userService di_userService;
    
    @Override
    @ApiOperation("查询司法组织机构-被申请人分页列表")
    @SaCheckPermission("di_rel_dept_target_list")
    public ResponseDTO list(Di_rel_dept_targetPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        Page<Di_rel_dept_target> page = this.di_rel_dept_targetService.findAll(pageInfo);
        List list = new ArrayList();
        if (!page.isEmpty()) {
            for (Di_rel_dept_target di_rel_dept_target : page) {
                di_rel_dept_target.geneText();
                list.add(di_rel_dept_target);
            }
        }
        PageDataResponse p = new PageDataResponse(list, page.getTotalElements(), page.getSize(), pageInfo.getPageNumber()<=1 ? 1 : pageInfo.getPageNumber());
        return ResponseDTO.succData(p);
    }

    @Override
    @ApiOperation("查看司法组织机构-被申请人")
    @SaCheckPermission("di_rel_dept_target_view")
    public ResponseDTO view(String id) {
        Assert.notNull(id, "id不能为空");
        Di_rel_dept_target di_rel_dept_target  = di_rel_dept_targetService.getById(id);
        if (di_rel_dept_target != null) {
            di_rel_dept_target.geneText();
        }
        return ResponseDTO.succData(di_rel_dept_target);
    }

    @Override
    @ApiOperation("删除司法组织机构-被申请人")
    @SaCheckPermission("di_rel_dept_target_del")
    public ResponseDTO delete(String id) {
        Assert.notNull(id, "id不能为空");
        di_rel_dept_targetService.removeById(id);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation("保存或修改司法组织机构-被申请人")
    @SaCheckPermission("di_rel_dept_target_save")
    public ResponseDTO save(Di_rel_dept_target di_rel_dept_target) {
        Assert.notNull(di_rel_dept_target, "di_rel_dept_target不能为空");
        di_rel_dept_targetService.saveOrUpdate(di_rel_dept_target);
        return ResponseDTO.succ();
    }
    
    @Override
    @ApiOperation(value="批量删除司法组织机构-被申请人")
    @SaCheckPermission("di_rel_dept_target_del")
    public ResponseDTO batchDel(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "ids不能为空");
        List<Integer> list = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        di_rel_dept_targetService.removeByIds(list);
        return ResponseDTO.succ();
    }
    
    @Override
    @ApiOperation(value="导出excel")
    @SaCheckPermission("di_rel_dept_target_list")
    public void output(HttpServletResponse response, Di_rel_dept_targetPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo不能为空");
        String title = "司法组织机构-被申请人";
        String[] heads = {"序号","名称","行政区域id","联系人id"};
        String[] fields = {"id","orgname","adid","contactuse"};
        Page<Di_rel_dept_target> page = this.di_rel_dept_targetService.findAll(pageInfo);
        ExcelUtil.exportXls(title, heads, fields, page.getContent(), response);
    }
            
    @Override
    @ApiOperation(value="导出excel模板")
    public void exportExcelTemplate(HttpServletResponse response) {
        String title = "司法组织机构-被申请人";
        //id自增或list从表可自行删除，需与导入项一致
        String[] heads = {"序号","名称","行政区域id","联系人id"};
        ExcelUtil.exportXls(title, heads, null, null, response);
    }
    
	@Override
	@ApiOperation(value="导入excel")
	public ResponseDTO importExcel(MultipartFile file) throws IOException {
        Assert.notNull(file, "file不能为空");
        //id自增或list从表可自行删除，需与下载的模板中导入项一致
        String[] fields = {"id","orgname","adid","contactuse"};
        List<Di_rel_dept_target> list = (List<Di_rel_dept_target>)ExcelUtil.Import(fields, file, Di_rel_dept_target.class);
        if(!CollectionUtils.isEmpty(list)) {
            this.di_rel_dept_targetService.saveAll(list);
        }
        return ResponseDTO.succ();
	}

    @Override
    public ResponseDTO queryAllTargetOrg() {
        return ResponseDTO.succData(this.di_rel_dept_targetService.queryAllTargetOrg());
    }

    @Override
    public ResponseDTO orgTree() {
        List<Di_rel_dept_target> deptList = this.di_rel_dept_targetService.findAll();
        if (!CollectionUtils.isEmpty(deptList)) {
            // 查询对应的数量
            List<String> userIdList = deptList.stream().filter(el -> ObjectUtil.isNotNull(el.getContactuser()))
                    .map(Di_rel_dept_target::getContactuser).collect(Collectors.toList());
            // 查询对应用户的数据
            List<Di_user> userList = di_userService.findUserByIds(userIdList);
            // 构建树层级结构
            List<Map<String, Object>> mapList = new ArrayList<>();
            deptList.stream().forEach(depart -> {
                Map<String,Object> objectMap = new HashMap<>();
                objectMap.putAll(BeanUtil.beanToMap(depart));
                String userId = depart.getContactuser();
                Di_user diUser = userList.stream().filter(user -> user.getId().equals(userId)).findAny().orElse(null);
                if (ObjectUtil.isNotNull(diUser)) {
                    objectMap.putAll(BeanUtil.beanToMap(diUser));
                }
                mapList.add(objectMap);
            });
            return ResponseDTO.succData(mapList);
        }
        return ResponseDTO.succData(ResponseDTO.wrap(500,"组织机构数据为空"));
    }

}
